﻿//using LibVLCSharp.Shared;
using SmartWeigh.ViewModel;
using SmartWeighMonitor;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Interop;
using System.Runtime.InteropServices;
using System.IO;
using SmartWeighMonitor.Utils;
using SmartWeighMonitor.Windows;
using System.Linq;
using UAVRadar;

namespace SmartWeigh.Controls
{
    /// <summary>
    /// MonitorPanel.xaml 的交互逻辑
    /// </summary>
    public partial class MonitorPanel : UserControl
    {
        public DatasteadDirectShowGraph_WithEventsMsg m_Graph = null;
        IntPtr winHandle = IntPtr.Zero;

        BitmapImage bgNormal;
        BitmapImage bgError;
        System.Windows.Forms.PictureBox m_pictureBox01;
        System.Windows.Forms.PictureBox m_pictureBox02;
        System.Windows.Forms.PictureBox m_pictureBox03;
        System.Windows.Forms.PictureBox m_pictureBox04;
        System.Windows.Forms.PictureBox m_pictureBox05;

        private int m_nPlayHandle01 = 0;
        private int m_nPlayHandle02 = 0;
        private int m_nPlayHandle03 = 0;


        private uint iLastErr = 0;
        private Int32 m_lUserID = -1;
        private bool m_bInitSDK = false;
        private bool m_bRecord = false;
        private bool m_bTalk = false;
        private Int32 m_lRealHandle = -1;
        private int lVoiceComHandle = -1;
        private string str;

        CHCNetSDK.REALDATACALLBACK RealData = null;
        CHCNetSDK.LOGINRESULTCALLBACK LoginCallBack = null;
        public CHCNetSDK.NET_DVR_PTZPOS m_struPtzCfg;
        public CHCNetSDK.NET_DVR_USER_LOGIN_INFO struLogInfo;
        public CHCNetSDK.NET_DVR_DEVICEINFO_V40 DeviceInfo;

        public delegate void UpdateTextStatusCallback(string strLogStatus, IntPtr lpDeviceInfo);
        private Point origin;
        private Point start;
        private FullScreenHelper fullScreenHelper = null;
        private FullScreenInContainerHelper FullScreenInContainerHelper = null;
        public MonitorPanel()
        {
            InitializeComponent();
            TransformGroup group = new TransformGroup();

            ScaleTransform xform = new ScaleTransform();
            group.Children.Add(xform);

            TranslateTransform tt = new TranslateTransform();
            group.Children.Add(tt);

            //billImage.RenderTransform = group;

            //billImage.MouseWheel += image_MouseWheel;
            //billImage.MouseLeftButtonDown += image_MouseLeftButtonDown;
            //billImage.MouseLeftButtonUp += image_MouseLeftButtonUp;
            //billImage.MouseMove += image_MouseMove;


            m_pictureBox01 = new System.Windows.Forms.PictureBox();
            m_pictureBox02 = new System.Windows.Forms.PictureBox();
            m_pictureBox03 = new System.Windows.Forms.PictureBox();
            m_pictureBox04 = new System.Windows.Forms.PictureBox();
            m_pictureBox05 = new System.Windows.Forms.PictureBox();

            videoHost01.Child = m_pictureBox01;
            videoHost02.Child = m_pictureBox02;
            videoHost00.Child = m_pictureBox03;
            videoHost03.Child = m_pictureBox04;
            //videoHost05.Child = m_pictureBox05;
            
            this.Loaded += Control_Load;

            bgNormal = new BitmapImage(new Uri("Resources\\Images\\mk-02.png", UriKind.Relative));
            bgError = new BitmapImage(new Uri("Resources\\Images\\mk-03.png", UriKind.Relative));

            m_Graph = new DatasteadDirectShowGraph_WithEventsMsg();
            //m_Graph.m_AddToLog = AddToLog;
            //m_Graph.m_PictureFromMemoryBitmap = imgCaptureToMemoryBitmap;
            m_Graph.m_DisplayWindow = panel1;
            m_bInitSDK = CHCNetSDK.NET_DVR_Init();
            if (m_bInitSDK == false)
            {
                MessageBox.Show("NET_DVR_Init error!");
                return;
            }
        }

       

        private void Control_Load(object sender, RoutedEventArgs e)
        {
            VzClientSDK.VzLPRClient_Setup();
            MonitorPanel monitorPanel = (MonitorPanel)sender;
            if (null != monitorPanel.ItemData)
            {
                String video_url = monitorPanel.ItemData.VideoUrl;

                m_pictureBox01.MouseDoubleClick += OpenVideo1;
                m_pictureBox02.MouseDoubleClick += OpenVideo2;
                m_pictureBox03.MouseDoubleClick += OpenVideo3;
                m_pictureBox04.MouseDoubleClick += OpenVideo4;
                //billImage.Source = new BitmapImage(new Uri("http://www.qrhgstore.com:8080/guns/sysFileInfo/previewByObjectName?fileBucket=images&fileObjectName=1703647974390329346.jpg", UriKind.Absolute));
                String[] videoUrlArray;
                if (!"".Equals(video_url))
                {
                    videoUrlArray = video_url.Split(';');

                    foreach (String url in videoUrlArray)
                    {
                        string[] vs = url.Split(',');
                        //HikVideo_Login(vs[0]);
                        btnPreview_Click(vs[0], vs[1]);
                    }
                    //string[] vs = video_url.Split(',');
                    ////HikVideo_Login(vs[0]);
                    //btnPreview_Click(vs[0], vs[1]);


                    //if (videoUrlArray.Length > 0)
                    //{
                    //    String[] videoInfoArray = videoUrlArray[0].Split(',');

                    //    payVideo(1,m_pictureBox01, videoInfoArray);
                    //}
                    //if (videoUrlArray.Length > 1)
                    //{
                    //    String[] videoInfoArray = videoUrlArray[1].Split(',');
                    //    payVideo(2,m_pictureBox03, videoInfoArray);
                    //}
                    //if (videoUrlArray.Length > 2)
                    //{
                    //{
                    //    String[] videoInfoArray = videoUrlArray[2].Split(',');
                    //    payVideo(3, m_pictureBox04, videoInfoArray);
                    //}
                    //String hikVideo_url = App.GetConfig().HikVideo_URL1;
                    //if (hikVideo_url != null && !"".Equals(hikVideo_url))
                    //{

                    //}
                }
                //String personVideo_url = App.GetConfig().PersonVideo_URL;
                //if (null!=personVideo_url && !"".Equals(personVideo_url))
                //{
                //        m_Graph.CloseInterfaces();
                //    OpenURL(false);
                //}
                //String hikVideo_url = App.GetConfig().HikVideo_URL1;
                //if (hikVideo_url != null && !"".Equals(hikVideo_url))
                //{
                //    HikVideo_Login();
                //    btnPreview_Click();
                //}
            }
        }

        private void payVideo(int idx,System.Windows.Forms.PictureBox picBox, String[] info) 
        {
            string ip = info[0];
            short nPort = Int16.Parse(info[1]);
            string username = info[2];
            string pass = info[3];

            int handle = 0;
            handle = VzClientSDK.VzLPRClient_Open(ip, (ushort)nPort, username, pass);
            if (handle == 0)
            {
                return;
            }
            VzClientSDK.VzLPRClient_SetIsShowPlateRect(handle, 0);
            picBox.Image = null;
            if (idx == 1)
            {
                if (m_nPlayHandle01 > 0)
                {
                    VzClientSDK.VzLPRClient_StopRealPlay(m_nPlayHandle01);
                    m_nPlayHandle01 = 0;
                }
            }else if (idx == 2)
            {
                if (m_nPlayHandle02 > 0)
                {
                    VzClientSDK.VzLPRClient_StopRealPlay(m_nPlayHandle02);
                    m_nPlayHandle02 = 0;
                }
            }
            else if (idx == 2)
            {
                if (m_nPlayHandle03 > 0)
                {
                    VzClientSDK.VzLPRClient_StopRealPlay(m_nPlayHandle02);
                    m_nPlayHandle03 = 0;
                }
            }

            VzClientSDK.VzLPRClient_SetVideoVBR(handle, 5);
            int lprHandle1 = 0;
            if (picBox.Tag != null)
            {
                string sHandle = picBox.Tag.ToString();
                lprHandle1 = Int32.Parse(sHandle);
            }
            if (lprHandle1 > 0)
            {
                VzClientSDK.VzLPRClient_SetPlateInfoCallBack(lprHandle1, null, IntPtr.Zero, 0);
            }
            if (idx == 1)
            {
                m_nPlayHandle01 = VzClientSDK.VzLPRClient_StartRealPlay(handle, picBox.Handle);
                picBox.Tag = handle;
            }else if (idx == 2)
            {
                m_nPlayHandle02 = VzClientSDK.VzLPRClient_StartRealPlay(handle, picBox.Handle);
                picBox.Tag = handle;
            }
            else if (idx == 3)
            {
                m_nPlayHandle03 = VzClientSDK.VzLPRClient_StartRealPlay(handle, picBox.Handle);
                picBox.Tag = handle;
            }
        }

        [BindableAttribute(true)]
        public ItemViewModel ItemData
        {
            get { return (ItemViewModel)GetValue(ItemDataProperty); }
            set { SetValue(ItemDataProperty, value); }
        }
        public static ItemViewModel GetItemData(DependencyObject obj)
        {
            return (ItemViewModel)obj.GetValue(ItemDataProperty);
        }
        public static void SetItemData(DependencyObject obj, ItemViewModel value)
        {
            obj.SetValue(ItemDataProperty, value);
        }

        [BindableAttribute(true)]
        public string ErrorMessage
        {
            get { return (string)GetValue(ErrorMessageProperty); }
            set
            {
                SetValue(ErrorMessageProperty, value);
            }
        }
        public static string GetErrorMessage(DependencyObject obj)
        {
            return (string)obj.GetValue(ErrorMessageProperty);
        }
        public static void SetErrorMessage(DependencyObject obj, string value)
        {
            obj.SetValue(ErrorMessageProperty, value);
        }

        public static readonly DependencyProperty ItemDataProperty = DependencyProperty.Register("ItemData", typeof(ItemViewModel), typeof(MonitorPanel), new PropertyMetadata(new PropertyChangedCallback(OnItemChange)));
        //定义一个依赖属性 ErrorMessage，并将其注册到 MonitorPanel 类中。依赖属性是 WPF（Windows Presentation Foundation）中的一种特殊属性，它支持数据绑定、样式、动画等高级功能。
        public static readonly DependencyProperty ErrorMessageProperty = DependencyProperty.Register("ErrorMessage", typeof(String), typeof(MonitorPanel), new PropertyMetadata(new PropertyChangedCallback(OnErrorMessageChange)));


        static private void OnErrorMessageChange(DependencyObject d, DependencyPropertyChangedEventArgs e)//报警信息的展示隐藏
        {
            var control = d as MonitorPanel; // 获取 MonitorPanel 控件实例

            String message = control.ErrorMessage==null ? "" : control.ErrorMessage;  // 获取 ErrorMessage 属性值，如果为 null 则转换为空字符串
            if ("".Equals(message)) // 根据错误信息更新 UI
            {
                control.txtErrorMessage.Text = ""; // 清空错误信息文本框
                control.btnError.Visibility = Visibility.Hidden; // 隐藏错误按钮

                control.errorBgImage.ImageSource = control.bgNormal;// 设置正常背景图片
            }
            else
            {
                control.txtErrorMessage.Text = message;// 显示错误信息
                control.btnError.Visibility = Visibility.Visible;// 显示错误按钮

                control.errorBgImage.ImageSource = control.bgError; // 设置错误背景图片
            }
        }
        static private void OnItemChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var control = d as MonitorPanel;

            string autoWeigh = control.ItemData.AutoWeigh;
            control.changeAutoWeigh(autoWeigh);

            return;
            string inStatus = control.ItemData.GateInStatus;
            string outStatus = control.ItemData.GateOutStatus;

            if (!String.IsNullOrEmpty(inStatus) && inStatus.Equals("1"))
            {
                control.gateIn01.Background = Brushes.Green;
                control.gateIn02.Background = Brushes.Green;
                control.gateIn03.Background = Brushes.Green;
            }
            else
            {
                control.gateIn01.Background = Brushes.Red;
                control.gateIn02.Background = Brushes.Red;
                control.gateIn03.Background = Brushes.Red;
            }

            if (!String.IsNullOrEmpty(outStatus) && outStatus.Equals("1"))
            {
                control.gateOut01.Background = Brushes.Green;
                control.gateOut02.Background = Brushes.Green;
                control.gateOut03.Background = Brushes.Green;
            }
            else
            {
                control.gateOut01.Background = Brushes.Red;
                control.gateOut02.Background = Brushes.Red;
                control.gateOut03.Background = Brushes.Red;
            }
        }


        public void changeLdStatus (String status)
        {
            this.ItemData.LDStatus = status;
            if ("open".Equals(status))
            {
                btnLDOpenAndClose.Content = "红外开启";
            }
            else
            {
                btnLDOpenAndClose.Content = "红外关闭";
            }
        }
        public void changeWeighStatus(String status)
        {
            this.ItemData.weighStatus = status;
            if ("allow".Equals(status))
            {
                btnWeighAllowAndNo.Content = "允许上磅";
            }
            else
            {
                btnWeighAllowAndNo.Content = "暂停过磅";
            }
        }



        public void changeAutoWeigh(String auto)
        {
            this.ItemData.AutoWeigh = auto;
            if ("true".Equals(auto))
            {
                AutoWeighButton.Content = "自动计量";
                AutoWeighButton.Background = Brushes.Green;
                btnReadCard.IsEnabled = false;
                btnOpen01.IsEnabled = false;
                btnOpen02.IsEnabled = false;
                btnSave.IsEnabled = false;
                btnClose01.IsEnabled = false;
                btnClose02.IsEnabled = false;
                btnLDOpenAndClose.IsEnabled = false;
                btnWeighAllowAndNo.IsEnabled = false;

                btnReadCard.Opacity = 0.5;
                btnOpen01.Opacity = 0.5;
                btnOpen02.Opacity = 0.5;
                btnSave.Opacity = 0.5;
                btnClose01.Opacity = 0.5;
                btnClose02.Opacity = 0.5;
                btnLDOpenAndClose.Opacity = 0.5;
                btnWeighAllowAndNo.Opacity = 0.5;
            }
            else
            {
                AutoWeighButton.Content = "手动计量";
                BrushConverter brushConverter = new BrushConverter();
                Brush brush = (Brush)brushConverter.ConvertFromString("#0c95b8");
                AutoWeighButton.Background = brush;

                btnReadCard.IsEnabled = true;
                btnOpen01.IsEnabled = true;
                btnOpen02.IsEnabled = true;
                btnSave.IsEnabled = true;
                btnClose01.IsEnabled = true;
                btnClose02.IsEnabled = true;
                btnLDOpenAndClose.IsEnabled = true;
                btnWeighAllowAndNo.IsEnabled=true;

                btnReadCard.Opacity = 1;
                btnOpen01.Opacity = 1;
                btnOpen02.Opacity = 1;
                btnSave.Opacity = 1;
                btnClose01.Opacity = 1;
                btnClose02.Opacity = 1;
                btnLDOpenAndClose.Opacity = 1;
                btnWeighAllowAndNo.Opacity=1;
            }
        }
        public void changeLDLeftStatus(String status)
        {
            if (!String.IsNullOrEmpty(status) && status.Equals("1"))
            {
                this.leftLD.Background = Brushes.Red;
            }
            else
            {
                this.leftLD.Background = Brushes.LightGreen;
            }

        }
        public void changeLDRightStatus(String status)
        {
            if (!String.IsNullOrEmpty(status) && status.Equals("1"))
            {
                this.rightLD.Background = Brushes.Red;
            }
            else
            {
                this.rightLD.Background = Brushes.LightGreen;
            }

        }
        public void changeGateInStatus(String inStatus)
        {
            if (!String.IsNullOrEmpty(inStatus) && inStatus.Equals("1"))
            {
                this.gateIn01.Background = Brushes.Green;
                this.gateIn02.Background = Brushes.Green;
                this.gateIn03.Background = Brushes.Green;
            }
            else
            {
                this.gateIn01.Background = Brushes.Red;
                this.gateIn02.Background = Brushes.Red;
                this.gateIn03.Background = Brushes.Red;
            }

        }
        public void changeGateOutStatus(String outStatus)
        {

            if (!String.IsNullOrEmpty(outStatus) && outStatus.Equals("1"))
            {
                this.gateOut01.Background = Brushes.Green;
                this.gateOut02.Background = Brushes.Green;
                this.gateOut03.Background = Brushes.Green;
            }
            else
            {
                this.gateOut01.Background = Brushes.Red;
                this.gateOut02.Background = Brushes.Red;
                this.gateOut03.Background = Brushes.Red;
            }
        }
        //public void showCar(bool show)
        //{
        //    if (show)
        //    {
        //        carImg.Opacity = 1;
        //    }
        //    else
        //    {
        //        carImg.Opacity = 0;
        //    }
        //}
        public void changeWeightStatus(String inStatus)
        {
            if (!String.IsNullOrEmpty(inStatus) && inStatus.Equals("稳定"))
            {
                this.txtWeight.Foreground = Brushes.Green;
            }
            else
            {
                this.txtWeight.Foreground = Brushes.Red;
            }

        }
        private void Button_Click_ReadCard(object sender, RoutedEventArgs e)
        {
            if (null == OnReadCard) return;
            OnReadCard(this, new ReadCardEventArgs(this.ItemData.Id));
        }
        public event ReadCardHandle OnReadCard;

        //定义委托
        public delegate void ReadCardHandle(object sender, ReadCardEventArgs e);
        public class ReadCardEventArgs : EventArgs
        {
            private string id;
            public ReadCardEventArgs(string id)
            {
                this.id = id;
            }
            public string Id
            {
                get { return id; }
            }
        }

        private void Button_Click_AutoWeigh(object sender, RoutedEventArgs e)
        {
            if (null == OnAutoWeighChange) return;
            OnAutoWeighChange(this, new AutoWeighEventArgs(this.ItemData.Id));
        }
        public event AutoWeighHandle OnAutoWeighChange;

        //定义委托
        public delegate void AutoWeighHandle(object sender, AutoWeighEventArgs e);
        public class AutoWeighEventArgs : EventArgs
        {
            private string id;
            public AutoWeighEventArgs(string id)
            {
                this.id = id;
            }
            public string Id
            {
                get { return id; }
            }
        }


        private void Button_Click_ReadWeight(object sender, RoutedEventArgs e)
        {
            if (null == OnReadWeight) return;
            OnReadWeight(this, new ReadWeightEventArgs(this.ItemData));
        }
        public event ReadWeightHandle OnReadWeight;

        //定义委托
        public delegate void ReadWeightHandle(object sender, ReadWeightEventArgs e);
        public class ReadWeightEventArgs : EventArgs
        {
            private ItemViewModel _data;
            public ReadWeightEventArgs(ItemViewModel data)
            {
                this._data = data;
            }
            public ItemViewModel Data
            {
                get { return _data; }
            }
        }

        
         private void Button_Click_SaveWeight(object sender, RoutedEventArgs e)
        {
            if (null == OnSaveWeight) return;
            OnSaveWeight(this, new SaveWeightEventArgs(this.ItemData));
        }
        public event SaveWeightHandle OnSaveWeight;
        public delegate void SaveWeightHandle(object sender,SaveWeightEventArgs e);
        public class SaveWeightEventArgs : EventArgs
        {
            private ItemViewModel _data;
            public SaveWeightEventArgs(ItemViewModel data)
            {
                this._data = data;
            }
            public ItemViewModel Data
            {
                get { return _data; }
            }
        }

        /*
        //定义委托
        public delegate void ReadWeightHandle(object sender, ReadWeightEventArgs e);
        public class AutoWeightEventArgs : EventArgs
        {
            private ItemViewModel _data;
            public AutoWeightEventArgs(ItemViewModel data)
            {
                this._data = data;
            }
            public ItemViewModel Data
            {
                get { return _data; }
            }
        }*/

        private void Button_Click_ErrorDeal(object sender, RoutedEventArgs e)
        {
            if (null == OnErrorDeal) return;
            OnErrorDeal(this, new ErrorDealEventArgs(this.ItemData));
        }
        public event ErrorDealHandle OnErrorDeal;

        //定义委托
        public delegate void ErrorDealHandle(object sender, ErrorDealEventArgs e);
        public class ErrorDealEventArgs : EventArgs
        {
            private ItemViewModel _data;
            public ErrorDealEventArgs(ItemViewModel data)
            {
                this._data = data;
            }
            public ItemViewModel data
            {
                get { return _data; }
            }
        }
        private void OpenVideo1(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            //openVideoInNewWindow();
            if (fullScreenHelper == null)
            {
                fullScreenHelper = new FullScreenHelper(m_pictureBox01);
                fullScreenHelper.FullScreen(true);
            }
            else
            {
                fullScreenHelper.FullScreen(false);
                fullScreenHelper = null;
            }

         
    }

        private void OpenVideo2(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (fullScreenHelper == null)
            {
                fullScreenHelper = new FullScreenHelper(m_pictureBox02);
                fullScreenHelper.FullScreen(true);
            }
            else
            {
                fullScreenHelper.FullScreen(false);
                fullScreenHelper = null;
            }
        }
        private void OpenVideo3(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (fullScreenHelper == null)
            {
                fullScreenHelper = new FullScreenHelper(m_pictureBox03);
                fullScreenHelper.FullScreen(true);
            }
            else
            {
                fullScreenHelper.FullScreen(false);
                fullScreenHelper = null;
            }
        }
        private void OpenVideo4(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (fullScreenHelper == null)
            {
                fullScreenHelper = new FullScreenHelper(m_pictureBox04);
                fullScreenHelper.FullScreen(true);
            }
            else
            {
                fullScreenHelper.FullScreen(false);
                fullScreenHelper = null;
            }
        }
       
        private void pictureBox1_MouseWheel(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            System.Drawing.Size t = m_pictureBox01.Size;
            if (e.Delta < 0)
            {
                this.m_pictureBox01.Width = this.m_pictureBox01.Width * 9 / 10;
                this.m_pictureBox01.Height = this.m_pictureBox01.Height * 9 / 10;
            }
            else
            {
                this.m_pictureBox01.Width = this.m_pictureBox01.Width * 11 / 10;

} }
        //    public void openVideoInNewWindow(string url)
        //{
        //    if (null == OnOpenVideo) return;
        //    OnOpenVideo(this, new OpenClientVideoEventArgs(this.ItemData.Id, url));
        //}
        //public event OpenClientVideoHandle OnOpenVideo;
        //public delegate void OpenClientVideoHandle(object sender, OpenClientVideoEventArgs e);
        //public class OpenClientVideoEventArgs : EventArgs
        //{
        //    private string _id;
        //    private string _url;
        //    public OpenClientVideoEventArgs(string id , string url)
        //    {
        //        this._id = id;
        //        this._url = url;
        //    }
        //    public string Id
        //    {
        //        get { return _id; }
        //    }
        //    public string url
        //    {
        //        get { return _url; }
        //    }     
        //}
        private void Button_Click_OpenDoor01(object sender, RoutedEventArgs e)
        {
            changeClientDoorStatus("in", "open");
        }
        private void Button_Click_CloseDoor01(object sender, RoutedEventArgs e)
        {
            changeClientDoorStatus("in", "close");
        }
        private void Button_Click_OpenDoor02(object sender, RoutedEventArgs e)
        {
            changeClientDoorStatus("out", "open");
        }

        private void Button_Click_CloseDoor02(object sender, RoutedEventArgs e)
        {
            changeClientDoorStatus("out", "close");
        }

        private void changeClientDoorStatus(string inOut,string status)
        {
            if ("in".Equals(inOut))
            {
                if ("open".Equals(status))
                {
                    changeGateInStatus("1");
                }
                else if ("close".Equals(status))
                {
                    changeGateInStatus("0");
                }
            }else if ("out".Equals(inOut))
            {
                if ("open".Equals(status))
                {
                    changeGateOutStatus("1");
                }
                else if ("close".Equals(status))
                {
                    changeGateOutStatus("0");
                }
            }
            if (null == OnChangeClientDoorStatus) return;
            OnChangeClientDoorStatus(this, new ChangeClientDoorStatusEventArgs(this.ItemData, inOut, status));
        }

        public event ChangeClientDoorStatusHandle OnChangeClientDoorStatus;
        public delegate void ChangeClientDoorStatusHandle(object sender, ChangeClientDoorStatusEventArgs e);

        public class ChangeClientDoorStatusEventArgs : EventArgs
        {
            private ItemViewModel _data;
            private string _inOut;
            private string _status;
            public ChangeClientDoorStatusEventArgs(ItemViewModel data, string inOut, string status)
            {
                this._data = data;
                this._inOut = inOut;
                this._status = status;
            }
            public ItemViewModel Data
            {
                get { return _data; }
            }
            public string InOut
            {
                get { return _inOut; }
            }
            public string Status
            {
                get { return _status; }
            }
        }

        public bool OpenURL(bool OpenAsynchronously)
        {
            System.Windows.Forms.Application.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture; // to get a dot as decimal separator when entering the frame rate
            if (winHandle == IntPtr.Zero)
            {
                HwndSource hs = (HwndSource)PresentationSource.FromDependencyObject(this);
                //var _mainWindow = Application.Current.Windows.Cast<Window>().FirstOrDefault(window => window is MainWindow) as MainWindow;
                winHandle = hs.Handle;
            }
            //try
            {
                m_Graph.GetStandardDirectShowInterfaces(winHandle);

                m_Graph.AddToROT(); // to be able to spy the graph from GraphEdit, remove this statement for production


                if (!m_Graph.AddDatasteadFilterAndQueryFilterInterfaces())
                {
                    //AddToLog("error: failed to create Datastead RTSP filter instance");
                }
                else
                {
                    m_Graph.m_DatasteadRTSPConfigHelper.SetBool(RTSPFilter.RTSPConfigParam.RTSP_VideoStream_Enabled_bool, true);
                    m_Graph.m_DatasteadRTSPConfigHelper.SetBool(RTSPFilter.RTSPConfigParam.RTSP_AudioStream_Enabled_bool, false);
                    m_Graph.m_DatasteadRTSPConfigHelper.SetBool(RTSPFilter.RTSPConfigParam.RTSP_AudioStream_Recorded_bool, false);
                    m_Graph.m_DatasteadRTSPConfigHelper.SetBool(RTSPFilter.RTSPConfigParam.RTSP_VideoStream_Recorded_bool, false);
                    m_Graph.m_DatasteadRTSPConfigHelper.SetBool(RTSPFilter.RTSPConfigParam.RTSP_Source_AutoReconnect_bool, true);

                    m_Graph.m_DatasteadRTSPConfigHelper.SetInt(RTSPFilter.RTSPConfigParam.RTSP_Source_RTSPTransport_int, RTSPFilter.RTSPTransportMode_Auto);
                    m_Graph.m_DatasteadRTSPConfigHelper.SetBool(RTSPFilter.RTSPConfigParam.RTSP_VideoStream_Synchronized_bool, false);
                    m_Graph.m_DatasteadRTSPConfigHelper.SetInt(RTSPFilter.RTSPConfigParam.RTSP_Source_LowDelay_int, Convert.ToInt32(false)); // 0 = disabled, 1 = enabled

                    m_Graph.m_DatasteadRTSPConfigHelper.SetStr(RTSPFilter.RTSPConfigParam.RTSP_Source_AuthUser_str, App.GetConfig().PersonVideo_Username);
                    m_Graph.m_DatasteadRTSPConfigHelper.SetStr(RTSPFilter.RTSPConfigParam.RTSP_Source_AuthPassword_str, App.GetConfig().PersonVideo_Password);

                    string URL = App.GetConfig().PersonVideo_URL;

                    //m_Graph.GraphRunResult = GraphRunResultCallback;

                    if (OpenAsynchronously)
                    {
                        int hr = m_Graph.m_DatasteadRTSPConfigHelper.Action(RTSPFilter.RTSPConfigParam.RTSP_Action_OpenURLAsync, URL);
                        if (hr == 0)
                        {
                            //AddToLog("Connecting asynchronously...");
                        }
                    }
                    else
                    {
                        // Action (RTSP_Action_OpenURL) opens the URL synchrnously
                        //AddToLog("Connecting synchronously...");
                        //Application.DoEvents(); /// to update the log window
                        int hr = m_Graph.m_DatasteadRTSPConfigHelper.Action(RTSPFilter.RTSPConfigParam.RTSP_Action_OpenURL, URL);
                        //LogIfError(hr, "open URL synchronously");
                        if (hr == 0)
                        {
                            m_Graph.RunGraph();
                        }
                    }
                }
            }
            return true;
        }

        private void HikVideo_Login(String url)
        {
           
            if (m_lUserID < 0)
            {

                struLogInfo = new CHCNetSDK.NET_DVR_USER_LOGIN_INFO();

                //设备IP地址或者域名
                byte[] byIP = System.Text.Encoding.Default.GetBytes(url);
                struLogInfo.sDeviceAddress = new byte[129];
                byIP.CopyTo(struLogInfo.sDeviceAddress, 0);

                //设备用户名
                byte[] byUserName = System.Text.Encoding.Default.GetBytes(App.GetConfig().HikVideo_Username);
                struLogInfo.sUserName = new byte[64];
                byUserName.CopyTo(struLogInfo.sUserName, 0);

                //设备密码
                byte[] byPassword = System.Text.Encoding.Default.GetBytes(App.GetConfig().HikVideo_Password);
                struLogInfo.sPassword = new byte[64];
                byPassword.CopyTo(struLogInfo.sPassword, 0);

                struLogInfo.wPort = ushort.Parse(App.GetConfig().HikVideo_Port);//设备服务端口号

                if (LoginCallBack == null)
                {
                    LoginCallBack = new CHCNetSDK.LOGINRESULTCALLBACK(cbLoginCallBack);//注册回调函数                    
                }
                struLogInfo.cbLoginResult = LoginCallBack;
                struLogInfo.bUseAsynLogin = false; //是否异步登录：0- 否，1- 是 

                DeviceInfo = new CHCNetSDK.NET_DVR_DEVICEINFO_V40();

                //登录设备 Login the device
                m_lUserID = CHCNetSDK.NET_DVR_Login_V40(ref struLogInfo, ref DeviceInfo);
                if (m_lUserID < 0)
                {
                    iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                    str = "NET_DVR_Login_V40 failed, error code= " + iLastErr; //登录失败，输出错误号
                    MessageBox.Show(str);
                    return;
                }
                else
                {
                    //登录成功
                    //MessageBox.Show("Login Success!");
                    //btnLogin.Text = "Logout";
                    m_lUserID = -1;
                }

            }
            else
            {
                //注销登录 Logout the device
                if (m_lRealHandle >= 0)
                {
                    MessageBox.Show("Please stop live view firstly");
                    return;
                }

                if (!CHCNetSDK.NET_DVR_Logout(m_lUserID))
                {
                    iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                    str = "NET_DVR_Logout failed, error code= " + iLastErr;
                    MessageBox.Show(str);
                    return;
                }
                m_lUserID = -1;
                //btnLogin.Text = "Login";
            }
            return;
        }

        public void cbLoginCallBack(int lUserID, int dwResult, IntPtr lpDeviceInfo, IntPtr pUser)
        {
            string strLoginCallBack = "登录设备，lUserID：" + lUserID + "，dwResult：" + dwResult;

            if (dwResult == 0)
            {
                uint iErrCode = CHCNetSDK.NET_DVR_GetLastError();
                strLoginCallBack = strLoginCallBack + "，错误号:" + iErrCode;
            }

            //下面代码注释掉也会崩溃
            if (true)
            {
                object[] paras = new object[2];
                paras[0] = strLoginCallBack;
                paras[1] = lpDeviceInfo;
                //labelLogin.BeginInvoke(new UpdateTextStatusCallback(UpdateClientList), paras);
            }
            else
            {
                //创建该控件的主线程直接更新信息列表 
                //UpdateClientList(strLoginCallBack, lpDeviceInfo);
            }

        }

        public void RealDataCallBack(Int32 lRealHandle, UInt32 dwDataType, IntPtr pBuffer, UInt32 dwBufSize, IntPtr pUser)
        {
            if (dwBufSize > 0)
            {
                byte[] sData = new byte[dwBufSize];
                Marshal.Copy(pBuffer, sData, 0, (Int32)dwBufSize);

                string str = "实时流数据.ps";
                FileStream fs = new FileStream(str, FileMode.Create);
                int iLen = (int)dwBufSize;
                fs.Write(sData, 0, iLen);
                fs.Close();
            }
        }

        private void btnPreview_Click(String url,String box)
        {

            if (m_lUserID < 0)
            {

                struLogInfo = new CHCNetSDK.NET_DVR_USER_LOGIN_INFO();

                //设备IP地址或者域名
                byte[] byIP = System.Text.Encoding.Default.GetBytes(url);
                struLogInfo.sDeviceAddress = new byte[129];
                byIP.CopyTo(struLogInfo.sDeviceAddress, 0);

                //设备用户名
                byte[] byUserName = System.Text.Encoding.Default.GetBytes(App.GetConfig().HikVideo_Username);
                struLogInfo.sUserName = new byte[64];
                byUserName.CopyTo(struLogInfo.sUserName, 0);

                //设备密码
                byte[] byPassword = System.Text.Encoding.Default.GetBytes(App.GetConfig().HikVideo_Password);
                struLogInfo.sPassword = new byte[64];
                byPassword.CopyTo(struLogInfo.sPassword, 0);

                struLogInfo.wPort = ushort.Parse(App.GetConfig().HikVideo_Port);//设备服务端口号

                if (LoginCallBack == null)
                {
                    LoginCallBack = new CHCNetSDK.LOGINRESULTCALLBACK(cbLoginCallBack);//注册回调函数                    
                }
                struLogInfo.cbLoginResult = LoginCallBack;
                struLogInfo.bUseAsynLogin = false; //是否异步登录：0- 否，1- 是 

                DeviceInfo = new CHCNetSDK.NET_DVR_DEVICEINFO_V40();

                //登录设备 Login the device
                m_lUserID = CHCNetSDK.NET_DVR_Login_V40(ref struLogInfo, ref DeviceInfo);
                if (m_lUserID < 0)
                {
                    iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                    str = "NET_DVR_Login_V40 failed, error code= " + iLastErr; //登录失败，输出错误号
                    MessageBox.Show(str);
                    return;
                }
                else
                {
                    //登录成功
                    //MessageBox.Show("Login Success!");
                    //btnLogin.Text = "Logout";
                    
                }

            }
            else
            {
                //注销登录 Logout the device
                if (m_lRealHandle >= 0)
                {
                    MessageBox.Show("Please stop live view firstly");
                    return;
                }

                if (!CHCNetSDK.NET_DVR_Logout(m_lUserID))
                {
                    iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                    str = "NET_DVR_Logout failed, error code= " + iLastErr;
                    MessageBox.Show(str);
                    return;
                }
               
                //btnLogin.Text = "Login";
            }
            


            if (m_lRealHandle < 0)
            {
                CHCNetSDK.NET_DVR_PREVIEWINFO lpPreviewInfo = new CHCNetSDK.NET_DVR_PREVIEWINFO();
                if ("01".Equals(box))
                {
                    lpPreviewInfo.hPlayWnd = m_pictureBox01.Handle;//预览窗口
                }else if ("02".Equals(box))
                {
                    lpPreviewInfo.hPlayWnd = m_pictureBox02.Handle;//预览窗口
                }
                else if ("03".Equals(box))
                {
                    lpPreviewInfo.hPlayWnd = m_pictureBox03.Handle;//预览窗口
                }
                else if ("04".Equals(box))
                {
                    lpPreviewInfo.hPlayWnd = m_pictureBox04.Handle;//预览窗口
                }
                lpPreviewInfo.lChannel = Int16.Parse("1");//预te览的设备通道
                lpPreviewInfo.dwStreamType = 1;//码流类型：0-主码流，1-子码流，2-码流3，3-码流4，以此类推
                lpPreviewInfo.dwLinkMode = 0;//连接方式：0- TCP方式，1- UDP方式，2- 多播方式，3- RTP方式，4-RTP/RTSP，5-RSTP/HTTP 
                lpPreviewInfo.bBlocked = true; //0- 非阻塞取流，1- 阻塞取流
                lpPreviewInfo.dwDisplayBufNum = 1; //播放库播放缓冲区最大缓冲帧数
                lpPreviewInfo.byProtoType = 0;
                lpPreviewInfo.byPreviewMode = 0;

                //if (textBoxID.Text != "")
                //{
                //    lpPreviewInfo.lChannel = -1;
                //    byte[] byStreamID = System.Text.Encoding.Default.GetBytes(textBoxID.Text);
                //    lpPreviewInfo.byStreamID = new byte[32];
                //    byStreamID.CopyTo(lpPreviewInfo.byStreamID, 0);
                //}


                if (RealData == null)
                {
                    RealData = new CHCNetSDK.REALDATACALLBACK(RealDataCallBack);//预览实时流回调函数
                }

                IntPtr pUser = new IntPtr();//用户数据

                //打开预览 Start live view 
                m_lRealHandle = CHCNetSDK.NET_DVR_RealPlay_V40(m_lUserID, ref lpPreviewInfo, null/*RealData*/, pUser);
                if (m_lRealHandle < 0)
                {
                    iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                    str = "NET_DVR_RealPlay_V40 failed, error code= " + iLastErr; //预览失败，输出错误号
                    MessageBox.Show(str);
                    return;
                }
                else
                {
                    //预览成功
                    //btnPreview.Text = "Stop Live View";
                    m_lUserID = -1;
                    m_lRealHandle = -1;
                }
            }
            else
            {
                //停止预览 Stop live view 
                if (!CHCNetSDK.NET_DVR_StopRealPlay(m_lRealHandle))
                {
                    iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                    str = "NET_DVR_StopRealPlay failed, error code= " + iLastErr;
                    MessageBox.Show(str);
                    return;
                }
                m_lRealHandle = -1;
                //btnPreview.Text = "Live View";

            }
            return;
        }

     

        private void Button_Click_LDOpen(object sender, RoutedEventArgs e)
        {
            if (null == OnChangeLDOpen) return;
            OnChangeLDOpen(this, new ChangeLDOpenEventArgs(this.ItemData.Id));
        }
        public event ChangeLDOpenHandle OnChangeLDOpen;
        public delegate void ChangeLDOpenHandle(object sender, ChangeLDOpenEventArgs e);
        public class ChangeLDOpenEventArgs : EventArgs
        {
            private string id;
            private string status;
            public ChangeLDOpenEventArgs(string id)
            {
                this.id = id;
            }
            public string Id
            {
                get { return id; }
            }
           
        }
        private void Button_Click_LDClose(object sender, RoutedEventArgs e)
        {
            if (null == OnChangeLDClose) return;
            OnChangeLDClose(this, new ChangeLDCloseEventArgs(this.ItemData.Id));
        }

        public event ChangeLDCloseHandle OnChangeLDClose;
        public delegate void ChangeLDCloseHandle(object sender, ChangeLDCloseEventArgs e);
        public class ChangeLDCloseEventArgs : EventArgs
        {
            private string id;
            public ChangeLDCloseEventArgs(string id)
            {
                this.id = id;
            }
            public string Id
            {
                get { return id; }
            }

        }

        private void Image_OnMouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left && e.ClickCount == 2)
            {
                Image image = (Image)sender;
                VideoWindow videoWindow = new VideoWindow();
                videoWindow.getVideoUrl(image.Source);
                videoWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                videoWindow.Show();
            }
          
        }

        private void Button_Click_WeighPermit(object sender, RoutedEventArgs e)//允许上磅
        {
            if (null == OnChangeWeighPermit) return;
            OnChangeWeighPermit(this,new ChangeWeighPermitHandleEventArgs(this.ItemData.Id));//this代表触发事件的对象（通常是事件的源对象）
        }
        public event ChangeWeighPermitHandle OnChangeWeighPermit;
        public delegate void ChangeWeighPermitHandle(object sender,ChangeWeighPermitHandleEventArgs e);
        public class ChangeWeighPermitHandleEventArgs : EventArgs
        {
            private string id;
            public ChangeWeighPermitHandleEventArgs(string id)
            {
                this.id = id;
            }
            public string Id
            {
                get { return id; }
            }
        }
        private void Button_Click_LDOpenAndClose(object sender, RoutedEventArgs e)//红外开启
        {

            if (null == OnChangeLDOpenAndClose) return;
            OnChangeLDOpenAndClose(this, new ChangeLDOpenAndCloseEventArgs(this.ItemData.Id));
        }
        public event ChangeLDOpenAndCloseHandle OnChangeLDOpenAndClose;//这是一个事件声明，名为 OnChangeLDOpenAndClose，类型为 ChangeLDOpenAndCloseHandle。事件使用 event 关键字声明，表示该事件可以被其他对象订阅。
        public delegate void ChangeLDOpenAndCloseHandle(object sender, ChangeLDOpenAndCloseEventArgs e);
        public class ChangeLDOpenAndCloseEventArgs : EventArgs
        {
            private string id;
            public ChangeLDOpenAndCloseEventArgs(string id)
            {
                this.id = id;
            }
            public string Id
            {
                get { return id; }
            }

        }



        //private void image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        //{
        //    billImage.ReleaseMouseCapture();
        //}

        //private void image_MouseMove(object sender, MouseEventArgs e)
        //{
        //    if (!billImage.IsMouseCaptured) return;

        //    var tt = (TranslateTransform)((TransformGroup)billImage.RenderTransform).Children.First(tr => tr is TranslateTransform);
        //    Vector v = start - e.GetPosition(border);
        //    tt.X = origin.X - v.X;
        //    tt.Y = origin.Y - v.Y;
        //}

        //private void image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        //{
        //    billImage.CaptureMouse();
        //    var tt = (TranslateTransform)((TransformGroup)billImage.RenderTransform).Children.First(tr => tr is TranslateTransform);
        //    start = e.GetPosition(border);
        //    origin = new Point(tt.X, tt.Y);
        //}

        //private void image_MouseWheel(object sender, MouseWheelEventArgs e)
        //{
        //    TransformGroup transformGroup = (TransformGroup)billImage.RenderTransform;
        //    ScaleTransform transform = (ScaleTransform)transformGroup.Children[0];

        //    double zoom = e.Delta > 0 ? .2 : -.2;
        //    transform.ScaleX += zoom;
        //    transform.ScaleY += zoom;
        //}
        //private void image_MouseMove(object sender, MouseEventArgs e)
        //{
        //    var center = e.GetPosition(billImage);
        //    var length = MagnifierCircle.ActualWidth*10;
        //    var radius = length / 2;
        //    var viewboxRect = new Rect(center.X - radius, center.Y - radius, length, length);
        //    MagnifierBrush.Viewbox = viewboxRect;
        //    MagnifierCircle.SetValue(Canvas.LeftProperty, center.X - MagnifierCircle.ActualWidth / 2);
        //    MagnifierCircle.SetValue(Canvas.TopProperty, center.Y - MagnifierCircle.ActualHeight / 2);

        //}

        //private void image_MouseEnter(object sender, MouseEventArgs e)
        //{
        //    MagnifierCircle.Visibility = Visibility.Visible;
        //}

        //private void image_MouseLeave(object sender, MouseEventArgs e)
        //{
        //    MagnifierCircle.Visibility = Visibility.Hidden;
        //}
        //public static void BringToFront(Image element)//图片置于最顶层显示
        //{
        //    if (element == null) return;


        //    Canvas parent = element.Parent as Canvas;
        //    if (parent == null) return;


        //    var maxZ = parent.Children.OfType<UIElement>()//linq语句，取Zindex的最大值
        //      .Where(x => x != element)
        //      .Select(x => Canvas.GetZIndex(x))
        //      .Max();
        //    Canvas.SetZIndex(element, maxZ + 1);
        //}

    }
}
